<?php

class DefaultController extends Controller
{       
        
        //for ftp
  
        

        private $base_url = 'http://localhost/vqm/oe-backend';
        private $base_dir = 'images/';
        private $thumb_dir = 'images/thumb/';
        private $image;
        private $image_type;
        
        
        private function mk_directory($path, $basepath){
            $fullpath = $basepath;
            //echo $fullpath;
            //exit();
            //chmod(substr($fullpath,0,-1), 0777);
            $parts = explode("/",$path);
            foreach($parts as $part){
                if($part != '' ){
                    $fullpath .= $part.'/';
                    if(!is_dir($fullpath)){
                        mkdir($fullpath, 0777,true);
                    }
                }
            }
            if($fullpath == $this->base_dir){
                return false;
            }
            else{
                return $fullpath;
            }
        }

        public function actionIndex()
	{   
            //Upload no ftp
            $this->base_url = Yii::app()->baseUrl;
            if(isset($_FILES['image'])){
                $path_dir = $_POST['name'].'/'.date('Y').'/'.date('m').'/'.date('d');
                $fulldir = $this->base_dir.$path_dir;
                $file_name = str_replace(' ','',time().'-'. basename($_FILES['image']['name']));
                $full_thumb_dir = $this->thumb_dir.$path_dir;
                if(!is_dir($fulldir)){
                        $fulldir = $this->mk_directory($path_dir, $this->base_dir);
                    }
                if (move_uploaded_file($_FILES['image']['tmp_name'], $fulldir.'/'.$file_name)) { 
                    
                    if(preg_match('/icon/', $_POST['name']) == 1 || preg_match('/thumb/', $_POST['name']) ==1 || preg_match('/logo/', $_POST['name']) ==1){
                        $put_thumb = $this->create_thumb($this->base_url.'/'.$fulldir.'/'.$file_name, 50, $path_dir, $full_thumb_dir, $file_name);
                    }  
                    echo $this->base_url.'/'.$fulldir.'/'.$file_name;
                } else {
                    echo "error";
                }
            }
            elseif(isset($_POST['file_name'])){
                $filename = str_replace($this->base_url, '', $_POST['file_name']);
                $filename = '.'.$filename;
                //echo $filename;
                //exit();
                if(unlink($filename)){
                    echo 'success';
                }else{
                    echo 'false';
                }
            }


            else{

                $file_name = str_replace(' ','',time().'-'. basename($_FILES['profile']['name']));
                if(move_uploaded_file($_FILES['profile']['tmp_name'], 'files'.'/'.$file_name)) {
                    echo $this->base_url.'/files/'.$file_name;
                } else {
                    echo "error";
                }
            }
        }
        
        
        private function create_thumb($file, $scale, $path_dir, $full_thumb_dir, $file_name){
           $this->load($file);
           $this->scale($scale);
           $this->save('./temp/'.$file_name);
           if(!is_dir($full_thumb_dir)){
                $full_thumb_dir = $this->mk_directory($path_dir, $this->thumb_dir);
            }
            //echo $full_thumb_dir;
            //exit();
            //var_dump($this->image);
            $move = rename( './temp/'.$file_name, $full_thumb_dir.'/'.$file_name);
            return $move;
       } 
         
        /*
	public function actionIndex()
	{   
            
            
            $conn_id = ftp_connect($this->server);
            $login_result = ftp_login($conn_id, $this->username, $this->password);
            if($login_result == 1){  
                if(isset($_FILES['image'])){
                    $path_dir = $_POST['name'].'/'.date('Y').'/'.date('m').'/'.date('d');
                    $fulldir = $this->base_dir.$path_dir;
                    $full_thumb_dir = $this->thumb_dir.$path_dir;
                    $file_name = str_replace(' ','',time().'-'. basename($_FILES['image']['name']));
                    
                    if(!is_dir('ftp://'.$this->username.':'.$this->password.'@'.$fulldir)){
                        $fulldir = $this->make_directory($conn_id, $path_dir, $this->base_dir);
                    }
                    $put = ftp_put($conn_id, $fulldir.$file_name, $_FILES['image']['tmp_name'], FTP_BINARY);
                    
                    //create_thumb
                    if(preg_match('/icon/', $_POST['name']) == 1 || preg_match('/thumb/', $_POST['name']) ==1 || preg_match('/logo/', $_POST['name']) ==1){
                        $put_thumb = $this->create_thumb($_FILES['image']['tmp_name'], 50, $conn_id, $path_dir, $full_thumb_dir, $file_name);
                    }

                    if($put == 1){
                        echo  str_replace('public_html/', '', $this->base_url.$fulldir.$file_name);    
                    }else{
                        echo 'false';
                    }
                }
                
                if(isset($_POST['file_name'])){
                    $filename = str_replace('http://img.gomo.vn', '', $_POST['file_name']);
                    $filename = '/public_html'.$filename;
                    //echo $filename;
                    //exit();
                    if(ftp_delete($conn_id, $filename)){
                        echo 'success';
                    }else{
                        echo 'false';
                    }
                }
                ftp_close($conn_id);
            }
        }

        //mkdir for ftp
        
       private function make_directory($conn_id,$path, $basepath){
            $fullpath = $basepath;
            $parts = explode("/",$path);
            foreach($parts as $part){
                if($part != '' ){
                    $fullpath .= $part.'/';
                    if(!is_dir('ftp://'.$this->username.':'.$this->password.'@'.$this->server.$fullpath)){
                        ftp_mkdir($conn_id, $fullpath);
                    }
                }
            }
            if($fullpath == $basepath){
                return false;
            }
            else{
                return $fullpath;
            }
        }
       
       private function create_thumb($file, $scale, $conn_id, $path_dir, $full_thumb_dir, $file_name){
           $this->load($file);
           $this->scale($scale);
           $this->save('./temp/'.$file_name);
           if(!is_dir('ftp://'.$this->username.':'.$this->password.'@'.$full_thumb_dir)){
                $full_thumb_dir = $this->make_directory($conn_id, $path_dir, $this->thumb_dir);
            }
            //echo $full_thumb_dir;
            //exit();
            //var_dump($this->image);
            $put = ftp_put($conn_id, $full_thumb_dir.$file_name, './temp/'.$file_name, FTP_BINARY);
            unlink('./temp/'.$file_name);
            return $put;
       } 
         * 
         */
        //resize image code
       private function load($filename) {
 
            $image_info = getimagesize($filename);
            $this->image_type = $image_info[2];
            if( $this->image_type == IMAGETYPE_JPEG ) {

               $this->image = imagecreatefromjpeg($filename);
            } elseif( $this->image_type == IMAGETYPE_GIF ) {

               $this->image = imagecreatefromgif($filename);
            } elseif( $this->image_type == IMAGETYPE_PNG ) {

               $this->image = imagecreatefrompng($filename);
            }
            
         }
         
      private function save($filename, $image_type=IMAGETYPE_JPEG, $compression=100, $permissions=null) {

            if( $image_type == IMAGETYPE_JPEG ) {
               imagejpeg($this->image,$filename,$compression);
            } elseif( $image_type == IMAGETYPE_GIF ) {

               imagegif($this->image,$filename);
            } elseif( $image_type == IMAGETYPE_PNG ) {

               imagepng($this->image,$filename);
            }
            if( $permissions != null) {

               chmod($filename,$permissions);
            }
         }
         
       private function output($image_type=IMAGETYPE_JPEG) {

            if( $image_type == IMAGETYPE_JPEG ) {
               imagejpeg($this->image);
            } elseif( $image_type == IMAGETYPE_GIF ) {

               imagegif($this->image);
            } elseif( $image_type == IMAGETYPE_PNG ) {

               imagepng($this->image);
            }
         }
         
        private function getWidth() {

             return imagesx($this->image);
          }
          
        private function getHeight() {

             return imagesy($this->image);
          }
          
        private function resizeToHeight($height) {

             $ratio = $height / $this->getHeight();
             $width = $this->getWidth() * $ratio;
             $this->resize($width,$height);
          }
          

        private function resizeToWidth($width) {
             $ratio = $width / $this->getWidth();
             $height = $this->getheight() * $ratio;
             $this->resize($width,$height);
          }

        private function scale($scale) {
             $width = $this->getWidth() * $scale/100;
             $height = $this->getheight() * $scale/100;
             $this->resize($width,$height);
          }

        private function resize($width,$height) {
             $new_image = imagecreatetruecolor($width, $height);
             imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
             $this->image = $new_image;
        }
        
        //end resize image code
}  


        //mkdir no ftp
        /*
        private function mk_directory($path, $basepath){
            $fullpath = $basepath;
            //echo $fullpath;
            //exit();
            //chmod(substr($fullpath,0,-1), 0777);
            $parts = explode("/",$path);
            foreach($parts as $part){
                if($part != '' ){
                    $fullpath .= $part.'/';
                    if(!is_dir($fullpath)){
                        mkdir($fullpath, 0777,true);
                    }
                }
            }
            if($fullpath == $this->base_dir){
                return false;
            }
            else{
                return $fullpath;
            }
        }
         * 
         */

        /*
        public function actionIndex()
	{   
            //Upload no ftp
            
            if(isset($_FILES['image'])){
                $path_dir = $_POST['name'].'/'.date('Y').'/'.date('m').'/'.date('d');
                $fulldir = $this->base_dir.$path_dir;
                $file_name = str_replace(' ','',time().'-'. basename($_FILES['image']['name']));
                
                if(!is_dir($fulldir)){
                        $fulldir = $this->mk_directory($path_dir);
                    }
                if (move_uploaded_file($_FILES['image']['tmp_name'], $fulldir.$file_name)) { 
                  echo $this->base_url.'/'.$fulldir.$file_name;
                } else {
                    echo "error";
                }
            }
            
            
            
            
            
            //FTP upload
            /*
            $conn_id = ftp_connect($this->server);
            $login_result = ftp_login($conn_id, $this->username, $this->password);
            if($login_result == 1){  
                if(isset($_FILES['image'])){
                    $path_dir = $_POST['name'].'/'.date('Y').'/'.date('m').'/'.date('d');
                    $fulldir = $this->base_dir.$path_dir;
                    $file_name = str_replace(' ','',time().'-'. basename($_FILES['image']['name']));
                    
                    if(!is_dir('ftp://'.$this->username.':'.$this->password.'@'.$fulldir)){
                        $fulldir = $this->make_directory($conn_id, $path_dir);
                    }
                    $put = ftp_put($conn_id, $fulldir.$file_name, $_FILES['image']['tmp_name'], FTP_BINARY);
                    if($put == 1){
                        echo str_replace('public_html/', '', $this->base_url.$fulldir.$file_name);
                    }else{
                        echo 'false';
                    }
                }
                
                if(isset($_POST['file_name'])){
                    $filename = str_replace($this->base_url, '', $_POST['file_name']);
                    $filename = '/public_html'.$filename;
                    //echo $filename;
                    //exit();
                    if(ftp_delete($conn_id, $filename)){
                        echo 'success';
                    }else{
                        echo 'false';
                    }
                }
                ftp_close($conn_id);
            }
            
            
            
        }
         */